package cn.zb.controller;

import cn.zb.common.util.RedisUtil;
import cn.zb.common.util.Result;
import cn.zb.entity.FlowQj;
import cn.zb.entity.auth.SysUser;
import cn.zb.service.FlowQjService;
import io.swagger.annotations.ApiOperation;
import org.dromara.warm.flow.core.dto.FlowParams;
import org.dromara.warm.flow.core.entity.Instance;
import org.dromara.warm.flow.core.entity.Task;
import org.dromara.warm.flow.core.entity.User;
import org.dromara.warm.flow.core.enums.SkipType;
import org.dromara.warm.flow.core.service.DefService;
import org.dromara.warm.flow.core.service.InsService;
import org.dromara.warm.flow.core.service.TaskService;
import org.dromara.warm.flow.core.service.UserService;
import org.dromara.warm.flow.orm.entity.FlowTask;
import org.dromara.warm.flow.orm.entity.FlowUser;
import org.dromara.warm.flow.ui.service.HandlerSelectService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 请假控制器
 *
 * @author:
 * @date: 2024-11-25 15:11
 **/
@RestController
@RequestMapping("qj")
public class QjController {
    @Resource
    FlowQjService qjService;

    @Resource
    RedisUtil redisUtil;
    @Resource
    InsService insService;
    @Resource
    TaskService taskService;
    @Resource
    UserService userService;

    @PostMapping("sq")
    @ApiOperation("请假任务申请")
    public Result sq(@RequestBody FlowQj qj,
                     @RequestHeader("token") String token){
        SysUser user = (SysUser) redisUtil.get("login:"+token);
        qj.setUid(user.getUserId());
        qjService.save(qj);
        // 开启任务
        FlowParams test = FlowParams.build().flowCode("test");
        // 设置创建者
        test.handler(user.getUserId()+"");
        test.message(qj.getContent());
        // 开启流程实例
        Instance instance = insService.start(String.valueOf(qj.getId()), test);
        // 直接流转下一个节点
        FlowParams params = FlowParams.build()
                .skipType(SkipType.PASS.getKey());
        Map<String,Object> cs = new HashMap<>();
        cs.put("day",qj.getDay());
        params.variable(cs);

        Instance in = insService.skipByInsId(instance.getId(), params);
        // 指定下一个流程的审批人id
        FlowTask task = new FlowTask();
        task.setDelFlag("0");
        task.setInstanceId(in.getId());
        Task one = taskService.getOne(task);
        FlowUser user1 = new FlowUser();
        user1.setAssociated(one.getId());
        User u = userService.getOne(user1);
        u.setCreateBy(String.valueOf(qj.getUid()));
        userService.updateById(u);
        return Result.ok("申请成功");
    }
}
